// pages/effects/popMenu/index.js

const db = wx.cloud.database()
const Time = require('../../../utils/time/TimeUtil2')
Page({

  /**
   * 页面的初始数据
   *    cardList: [{
      id: '1',
      name: '左滑试试吧', //标题
      text: "这是内容",
      jifen: 5, //积分
      aut: "筱恺",
      autid: '123456',
      pizhun: true, //对方是否批准完成任务
      zt: false, //是否完成任务
      xmove: 0,
    }, ], //数据
   */
  data: {
    cpcardList: [], //自己创建的任务
    cardList: [], //数据
    tab_lsit: ['未完成', '已完成', '审核任务'],
    curTab: 0, //使用未使用判断
  },
  //使用未使用
  tabNav(e) {
    let {
      index
    } = e.currentTarget.dataset;
    if (this.data.curTab === index || index === undefined) {
      return false;
    } else {
      this.setData({
        curTab: index,
      })
    }
    if (index == 0) {
      let ARr = this.data.yilist
      this.setData({
        list: ARr
      })
    } else {
      let ARr = this.data.weilist
      this.setData({
        list: ARr
      })
    }
  },

  //获取数据消息
  async getDatabuts() {
    let vale = wx.getStorageSync('autt').user
    console.log(vale._id);
    //获取自己的任务
    let ast = await db.collection('xiangta').where({
      autid: vale._id
    }).get()
    ast.data[0].dbarr.forEach((item, index) => {
      item.xmove = 0;
      item.id = index;
    })
    //获取给对方创建的任务
    let cpast = await db.collection('xiangta').where({
      cp: vale._id
    }).get()
    cpast.data[0].dbarr.forEach((item, index) => {
      item.xmove = 0;
      item.id = index;
    })
    this.setData({
      cardList: ast.data[0].dbarr.reverse(),
      cpcardList: cpast.data[0].dbarr.reverse(),
    })
  },
  /**
   * 处理touchstart事件
   */
  handleTouchStart(e) {
    this.startX = e.touches[0].pageX
  },

  /**
   * 处理touchend事件
   */
  handleTouchEnd(e) {
    if (e.changedTouches[0].pageX < this.startX && e.changedTouches[0].pageX - this.startX <= -30) {
      this.showDeleteButton(e)
    } else if (e.changedTouches[0].pageX > this.startX && e.changedTouches[0].pageX - this.startX < 30) {
      this.showDeleteButton(e)
    } else {
      this.hideDeleteButton(e)
    }
  },
  /**
   * 显示删除按钮
   */
  showDeleteButton: function (e) {
    let index = e.currentTarget.dataset.index;
    // console.log(index);
    this.setXmove(index, -65);
  },

  /**
   * 隐藏删除按钮
   */
  hideDeleteButton: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setXmove(index, 0);
  },

  /**
   * 设置movable-view位移
   */
  setXmove: function (index, xmove) {
    let {
      cardList
    } = this.data;
    cardList[index].xmove = xmove;
    this.setData({
      cardList: cardList
    })
    console.log(this.data.cardList)
  },

  /**
   * 处理movable-view移动事件
   */
  handleMovableChange: function (e) {
    if (e.detail.source === 'friction') {
      if (e.detail.x < -30) {
        this.showDeleteButton(e)
      } else {
        this.hideDeleteButton(e)
      }
    } else if (e.detail.source === 'out-of-bounds' && e.detail.x === 0) {
      this.hideDeleteButton(e)
    }
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.getDatabuts()

    wx.hideLoading()
  },
  //点击审核
  dianji(e) {
    console.log(e.currentTarget.dataset.sj);
    let data = e.currentTarget.dataset.sj
    if ((!data.pizhun) && data.zt) {
      debugger
      //弹出提示框
      wx.showActionSheet({
        alertText: data.name, //提示文案
        itemList: ['满意', '一般', '不满意'],
        success: res => {
          let jf = 0
          console.log(res.tapIndex)
          switch (res.tapIndex) {
            case 0: {
              //满分积分
              console.log('满意');
              jf += (data.jifen / 2)
            };
          case 1: {
            // 一般积分
            console.log('一般');
            jf += (data.jifen / 2)
            console.log(jf);
          }
          case 2: {
            // 0分
            console.log('不满意');
          }
          }
          this.shenherenwu(data.id, jf, res.tapIndex)
          //将数据修改
          let a = this.data.cpcardList
          a.reverse()[data.id].pizhun = true
          a[data.id].bz = res.tapIndex
          this.setData({
            cpcardList: a.reverse()
          })
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    }else{
      wx.showToast({
        title: '对方未完成',
        icon: 'error',
        duration: 2000
      })
    }
  },

  //调用数据库给对方加积分
  async shenherenwu(index, jifen, man) {
    let value = wx.getStorageSync('autt').user
    console.log(value);
    let a = await db.collection('xiangta').where({
      cp: value._id
    }).update({
      data: { //模版字符串动态的更改索引
        [`dbarr.${index}.pizhun`]: true,
        [`dbarr.${index}.bz`]: man,
      }
    })
    let users = await db.collection('users').where({
      cpid: value._id
    }).get()
    let arr = users.data[0].jfmingxi
    let str = '完成任务+' + jifen
    let date = Time.formatDatetime(new Date())
    let obj = {
      nr: str,
      time: date
    }
    console.log(obj);
    arr.unshift(obj)

    await db.collection('users').where({
      cpid: value._id
    }).update({
      // data 传入需要局部更新的数据
      data: {
        jf: db.command.inc(jifen),
        jfmingxi: arr
      },
    })
  },


  onShow: function () {

  },
  handleDelete(e) {
    let {
      id
    } = e.currentTarget.dataset;
    this.itemDel(id)
  },
  async itemDel(id) {
    let arrlist = this.data.cardList.reverse()
    await arrlist.forEach((item, index) => {
      if (item.id == id) {
        //完成任务
        arrlist[index].zt = true;
        let vale = wx.getStorageSync('autt').user
        db.collection('xiangta').where({
          autid: vale._id
        }).update({
          data: {
            //模版字符串动态的更改索引
            [`dbarr.${index}.zt`]: true
          },
          success: async (res) => {
            arrlist.reverse()
            this.setData({
              cardList: arrlist
            })
            wx.showToast({
              title: '完成任务咯好棒~',
              icon: 'success'
            })
          }
        })
        // this.data.cardList.splice(index, 1)
      }

    })
  },


  btnPop() {
    let stee = '/pages/shangdian/MissionAdd/index'
    wx.navigateTo({
      url: stee,
    });
  },

})